<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="78px">
      <el-form-item label="课程号" prop="courseNumber">
        <el-input v-model="queryParams.courseNumber" placeholder="请输入课程号" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课题级别" prop="rank">
        <el-input v-model="queryParams.rank" placeholder="请输入课题级别" clearable />
      </el-form-item>
      <el-form-item label="经费基准" prop="expenditure">
        <el-input v-model="queryParams.expenditure" placeholder="请输入经费基准" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="费用名称" prop="costname">
        <el-input v-model="queryParams.costname" placeholder="请输入费用名称" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['village:expenditure:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['village:expenditure:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['village:expenditure:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['village:expenditure:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="zongocated">
          当前项目总经费：{{ this.projectFund }}元
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" @click="Allocated">
          当前经费已使用：{{ this.price }}元
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="课程号" align="center" prop="courseNumber"/>
      <el-table-column label="教改项目" align="center" prop="villageEducationalReformName"/>
      <el-table-column label="课题级别" align="center" prop="rank">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.village_expenditure_grade" :value="scope.row.rank"/>
        </template>
      </el-table-column>
      <el-table-column label="经费基准" align="center" prop="expenditure"/>
      <el-table-column label="费用名称" align="center" prop="costname"/>
      <el-table-column label="报销金额" align="center" prop="reportForDeletion"/>
      <el-table-column label="剩余经费" align="center" prop="surplusFunds"/>
      <el-table-column label="报销人" align="center" prop="reportForDeletionName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-s-unfold" @click="selectdetailopen(scope.row)">详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['village:expenditure:edit']"
          >修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['village:expenditure:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 添加或修改教改项目结课对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" :inline="true">
        <el-form-item style="width: 350px" label="教改项目" prop="villageEducationalReformName">
          {{ location }}
        </el-form-item>
        <el-form-item label="课程号" prop="courseNumber">
          <el-input v-model="form.courseNumber" placeholder="请输入课程号"/>
        </el-form-item>
        <el-form-item style="width: 348px" label="课题级别" prop="rank">
          <el-select style="width: 204px" v-model="form.rank" placeholder="请选择课题级别">
            <el-option v-for="dict in dict.type.village_expenditure_grade" :key="dict.value" :label="dict.label"
                       :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经费基准" prop="expenditure">
          <el-input disabled v-model="form.expenditure" placeholder="请输入经费基准"/>
        </el-form-item>
        <el-form-item label="费用名称" prop="costname">
          <el-autocomplete
            class="inline-input"
            v-model="form.costname"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="报销金额" prop="reportForDeletion">
          <el-input v-model="form.reportForDeletion" placeholder="请输入报销金额"/>
        </el-form-item>
        <el-form-item label="任务书预算" prop="missionBookBudget">
          <el-input v-model="form.missionBookBudget" placeholder="请输入任务书预算"/>
        </el-form-item>
        <el-form-item label="剩余经费" prop="surplusFunds">
          <el-input disabled v-model="form.surplusFunds" placeholder="请输入剩余经费"/>
        </el-form-item>
        <el-form-item label="报销人" prop="reportForDeletionName" style="width: 500px">
          <el-input v-model="form.reportForDeletionName" placeholder="请输入报销人"/>
        </el-form-item>
        <el-form-item label="经济业务简述" prop="economicWork">
          <el-input v-model="form.economicWork" type="textarea" placeholder="请输入内容" style="width: 520px;"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" style="width: 520px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="详细信息" :visible.sync="detailopen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" inline>
        <el-form-item label="教改项目：" style="width: 700px">
          {{ form.villageEducationalReformName }}
        </el-form-item>
        <el-form-item label="课程号：" style="width: 300px">
          {{ form.courseNumber }}
        </el-form-item>
        <el-form-item label="课题级别：" >
          {{ form.rank }}
        </el-form-item>
        <el-form-item label="经费基准：" style="width: 300px">
          {{ form.rank }}
        </el-form-item>
        <el-form-item label="费用名称：" style="width: 300px" prop="costname">
          {{ form.costname }}
        </el-form-item>

        <el-form-item label="报销金额：" style="width: 300px" prop="reportForDeletion">
          {{ form.reportForDeletion }}
        </el-form-item>
        <el-form-item label="剩余经费：" style="width: 300px" prop="surplusFunds">
          {{ form.surplusFunds }}
        </el-form-item>
        <el-form-item label="任务书预算：" style="width: 300px" prop="missionBookBudget">
          {{ form.missionBookBudget }}
        </el-form-item>
        <el-form-item label="报销人：" style="width: 300px" prop="reportForDeletionName">
          {{ form.reportForDeletionName }}
        </el-form-item>
        <el-form-item label="经济业务简述：" prop="economicWork">
          <div style="width: 500px;">
          {{ form.economicWork }}
          </div>
        </el-form-item>
        <el-form-item label="备注：" style="white-space: normal; word-break: break-word;">

          <div style="width: 500px;">
            {{ form.remark }}
          </div>

        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listDetail,nolistDetail, getDetail, delDetail, addDetail, updateDetail } from '@/api/village/detail'
import { listReform, getReform } from '@/api/village/reform'
import { noListManage } from "@/api/village/manage";

export default {
  name: 'Detail',
  dicts: ['village_expenditure_grade'],
  data() {
    return {
      restaurants: [],

      expenselist: [],
      location: null,
      reportFor: 0,
      zijing: 0,
      isAddOREdit: true,
      detailopen: false,
      projectFund: 0,
      price: 0,
      reformList: [],
      options: [{
        value: '选项1',
        label: '黄金糕'
      }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教改项目结课表格数据
      detailList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        villageEducationalReformId: null,
        courseNumber: null,
        rank: null,
        expenditure: null,
        costname: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

        villageEducationalReformId: [
          { required: true, message: '教改项目不能为空', trigger: 'blur' }
        ],
        expenditure: [
          { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: ['blur'] }
        ],
        missionBookBudget: [
          { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: ['blur'] }
        ],

        courseNumber: [
          { required: true, message: '课程号不能为空', trigger: 'blur' }
        ],
        rank: [
          { required: true, message: '课题级别不能为空', trigger: 'blur' }
        ],
        costname: [
          { required: true, message: '费用名称不能为空', trigger: 'change' }
        ],
        reportForDeletion: [
          { required: true, message: '报销金额不能为空', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d+)?$/, // 正则表达式，匹配一个或多个数字，后面可跟一个小数点和一个或多个数字
            message: '请输入数字',
            trigger: ['input', 'blur']
          },
          {
            validator: (rule, value, callback) => {
              let min
              let max
              if (this.isAddOREdit) {

                min = parseFloat(this.form.reportForDeletion) + parseFloat(this.price)
                max = parseFloat(this.projectFund) - parseFloat(this.price) + parseFloat(this.reportFor)
                min = isNaN(min) ? 0 : min
                max = isNaN(max) ? 0 : max

                let zhi = max - this.form.reportForDeletion  - this.reportFor
                // max = zhi
                this.form.surplusFunds = isNaN(zhi) ? 0 :zhi

              } else {
                min = parseFloat(this.price) - parseFloat(this.reportFor) + parseFloat(this.form.reportForDeletion)
                max = parseFloat(this.projectFund) - parseFloat(this.price) + parseFloat(this.reportFor)
                min = isNaN(min) ? 0 : min
                max = isNaN(max) ? 0 : max
                console.log('min:', max)

                let zhi = max - parseFloat(this.form.reportForDeletion)

                this.form.surplusFunds = isNaN(zhi) ? 0 :zhi

              }

              if (min > parseFloat(this.projectFund)) {
                if (max === 0) {
                  callback(new Error(`报销金额已用尽`))
                } else {
                  callback(new Error(`报销金额不能超过${max}元`))
                }
              } else {
                callback() // 验证通过
              }
            },
            trigger: ['change', 'blur']
          }
        ],
        reportForDeletionName: [
          { required: true, message: '报销人不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.queryParams.villageEducationalReformId = this.$route.query.id
    this.getList()
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {

      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadAll() {

      return this.expenselist

    },
    handleSelect(item) {
      this.form.missionBookBudget = item.address
    },
    selectdetailopen(row) {
      getDetail(row.id).then(response => {

        this.form = response.data

        this.detailopen = true
      })
    },
    /** 查询教改项目结课列表 */
    getList() {
      this.loading = true
      listDetail(this.queryParams).then(response => {
        this.detailList = response.rows
        this.total = response.total
        this.loading = false
      })
      nolistDetail(this.queryParams).then(response => {
        this.price = 0
        response.rows.map((item) => {
          this.price = parseInt(this.price) + parseInt(item.reportForDeletion)
        })
      })
      getReform(this.$route.query.id).then(response => {
        this.projectFund = response.data.projectFund
        this.location = response.data.location
      })
      noListManage({}).then(response => {

        this.expenselist = response.rows.map(item => ({
          address: item.money,

          value: item.name
        }));
        this.restaurants = this.loadAll();
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {

      this.form = {
        id: null,
        villageEducationalReformId: null,
        courseNumber: null,
        rank: null,
        expenditure: null,
        costname: null,
        economicWork: null,
        reportForDeletion: null,
        surplusFunds: null,
        missionBookBudget: null,
        reportForDeletionName: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        isDelete: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加记账支出'
      this.isAddOREdit = true

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.isAddOREdit = false
      const id = row.id || this.ids
      getDetail(id).then(response => {
        this.form = response.data
        this.reportFor = this.form.reportForDeletion
        this.form.expenditure = this.projectFund
        this.open = true
        this.title = '修改记账支出'
      })

    },
    /** 提交按钮 */
    submitForm() {
      // this.form.projectFund = this.projectFund
      this.form.villageEducationalReformId = this.$route.query.id
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDetail(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
              this.price = 0
              this.projectFund = 0
              this.reportFor = 0
              this.zijing = 0
            })
          } else {
            addDetail(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
              this.price = 0
              this.projectFund = 0
              this.reportFor = 0
                this.zijing = 0
            })
          }
        }

      })

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除教改项目结课编号为"' + ids + '"的数据项？').then(function() {
        return delDetail(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('village/detail/export', {
        ...this.queryParams
      }, `detail_${new Date().getTime()}.xlsx`)
    },
    // 记账支出跳转
    skipDetail(row) {
      this.$router.push(`/expendituredetail?id=${row.id}`)
    },
    // 已使用的经费
    Allocated() {
      this.$message({
        message: '当前已花费' + this.price + '元，注意合理消费哦',
        type: 'success'
      })
    },
    zongocated() {
      this.$message({
        message: '项目总经费为' + this.projectFund,
        type: 'success'
      })
    }
  }
}
</script>
